<template>
  <div class="profile-page">
    <el-container>
      <el-header class="page-header">
        <h1 class="page-title">个人中心</h1>
      </el-header>
      
      <el-main>
        <div class="profile-content">
          <el-row :gutter="24">
            <!-- 左侧个人信息 -->
            <el-col :span="8">
              <el-card class="profile-card">
                <template #header>
                  <span class="card-title">个人信息</span>
                </template>
                
                <div class="profile-info">
                  <!-- 头像上传 -->
                  <div class="avatar-section">
                    <el-upload
                      class="avatar-uploader"
                      name="avatar"
                      :action="avatarUploadUrl"
                      :headers="uploadHeaders"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                      :on-error="handleAvatarError"
                      :before-upload="beforeAvatarUpload"
                      accept="image/*"
                    >
                      <el-avatar
                        :size="120"
                        :src="avatarUrl"
                        class="user-avatar"
                      >
                        <el-icon><User /></el-icon>
                      </el-avatar>
                      <div class="avatar-overlay">
                        <el-icon><Camera /></el-icon>
                        <span>更换头像</span>
                      </div>
                    </el-upload>
                  </div>
                  
                  <!-- 基本信息 -->
                  <div class="basic-info">
                    <h2 class="user-name">{{ userInfo.name }}</h2>
                    <p class="user-email">{{ userInfo.email }}</p>
                    <el-tag :type="userInfo.role === 'admin' ? 'danger' : 'primary'">
                      {{ getRoleText(userInfo.role) }}
                    </el-tag>
                  </div>
                  
                  <!-- 统计信息 -->
                  <div class="stats-info">
                    <div class="stat-item">
                      <span class="stat-number">{{ stats.totalLessonPlans }}</span>
                      <span class="stat-label">教案总数</span>
                    </div>
                    <div class="stat-item">
                      <span class="stat-number">{{ stats.publishedLessonPlans }}</span>
                      <span class="stat-label">已发布</span>
                    </div>
                    <div class="stat-item">
                      <span class="stat-number">{{ stats.draftLessonPlans }}</span>
                      <span class="stat-label">草稿</span>
                    </div>
                  </div>
                  
                  <!-- 注册时间 -->
                  <div class="register-info">
                    <el-icon><Calendar /></el-icon>
                    <span>{{ formatDate(userInfo.createdAt) }} 加入</span>
                  </div>
                </div>
              </el-card>
              
              <!-- 快捷操作 -->
              <el-card class="action-card">
                <template #header>
                  <span class="card-title">快捷操作</span>
                </template>
                
                <div class="quick-actions">
                  <el-button type="primary" @click="createLessonPlan" icon="Plus">
                    创建教案
                  </el-button>
                  <el-button @click="viewMyLessonPlans" icon="Document">
                    我的教案
                  </el-button>
                  <el-button @click="showEditProfile = true" icon="Edit">
                    编辑资料
                  </el-button>
                  <el-button @click="showChangePassword = true" icon="Key">
                    修改密码
                  </el-button>
                </div>
              </el-card>
            </el-col>
            
            <!-- 右侧内容区域 -->
            <el-col :span="16">
              <!-- 我的教案 -->
              <el-card class="content-card">
                <template #header>
                  <div class="card-header">
                    <span class="card-title">我的教案</span>
                    <el-button link type="primary" @click="viewMyLessonPlans">
                      查看全部
                    </el-button>
                  </div>
                </template>
                
                <div v-loading="loadingLessonPlans">
                  <el-table :data="recentLessonPlans" style="width: 100%">
                    <el-table-column prop="title" label="标题" min-width="200">
                      <template #default="{ row }">
                        <el-link
                          type="primary"
                          @click="viewLessonPlan(row._id)"
                          :underline="false"
                        >
                          {{ row.title }}
                        </el-link>
                      </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态" width="100">
                      <template #default="{ row }">
                        <el-tag
                          :type="getStatusTagType(row.status)"
                          size="small"
                        >
                          {{ getStatusText(row.status) }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column prop="views" label="浏览量" width="100" />
                    <el-table-column prop="updatedAt" label="更新时间" width="180">
                      <template #default="{ row }">
                        {{ formatDate(row.updatedAt) }}
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="150">
                      <template #default="{ row }">
                        <el-button
                          link
                          type="primary"
                          size="small"
                          @click="editLessonPlan(row._id)"
                        >
                          编辑
                        </el-button>
                        <el-button
                          link
                          type="danger"
                          size="small"
                          @click="deleteLessonPlan(row)"
                        >
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  
                  <el-empty
                    v-if="!loadingLessonPlans && recentLessonPlans.length === 0"
                    description="还没有创建教案"
                  />
                </div>
              </el-card>
              
              <!-- 最近活动 -->
              <el-card class="content-card">
                <template #header>
                  <span class="card-title">最近活动</span>
                </template>
                
                <div v-loading="loadingActivities">
                  <el-timeline>
                    <el-timeline-item
                      v-for="activity in recentActivities"
                      :key="activity.id"
                      :timestamp="formatDate(activity.createdAt)"
                      placement="top"
                    >
                      <div class="activity-item">
                        <el-icon class="activity-icon" :class="getActivityIconClass(activity.type)">
                          <component :is="getActivityIcon(activity.type)" />
                        </el-icon>
                        <span class="activity-content">{{ activity.content }}</span>
                      </div>
                    </el-timeline-item>
                  </el-timeline>
                  
                  <el-empty
                    v-if="!loadingActivities && recentActivities.length === 0"
                    description="暂无活动记录"
                  />
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-main>
    </el-container>
    
    <!-- 编辑个人资料对话框 -->
    <el-dialog
      v-model="showEditProfile"
      title="编辑个人资料"
      width="500px"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" disabled />
          <el-text type="info" size="small">邮箱不可修改</el-text>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showEditProfile = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateProfile" :loading="updating">
          保存
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="showChangePassword"
      title="修改密码"
      width="500px"
      @close="resetPasswordForm"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input
            v-model="passwordForm.currentPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showChangePassword = false">取消</el-button>
        <el-button type="primary" @click="handleChangePassword" :loading="changingPassword">
          修改密码
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadFile } from 'element-plus'
import {
  User,
  Camera,
  Calendar,
  Plus,
  Document,
  Edit,
  Key,
  DocumentAdd,
  Star,
  View,
  Delete
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { lessonPlanApi, type LessonPlan } from '@/api/lessonPlan'
import { userApi, type Activity } from '@/api/user'

const router = useRouter()
const authStore = useAuthStore()

// 表单引用
const editFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()

// 数据状态
const loadingLessonPlans = ref(false)
const loadingActivities = ref(false)
const updating = ref(false)
const changingPassword = ref(false)
const showEditProfile = ref(false)
const showChangePassword = ref(false)

// 用户信息
const userInfo = computed(() => authStore.user || {
  _id: '',
  name: '',
  email: '',
  role: 'student' as const,
  avatar: '',
  createdAt: ''
})

// 获取完整的头像URL
const avatarUrl = computed(() => {
  // 使用 store 的 avatarTimestamp 来强制更新
  const timestamp = authStore.avatarTimestamp
  
  if (!userInfo.value.avatar) return ''
  
  // 如果已经是完整URL，直接返回
  if (userInfo.value.avatar.startsWith('http')) {
    return `${userInfo.value.avatar}?t=${timestamp}`
  }
  
  // 开发环境下使用代理，直接返回相对路径
  // 生产环境需要配置 VITE_API_BASE_URL
  return `${userInfo.value.avatar}?t=${timestamp}`
})

// 统计信息
const stats = reactive({
  totalLessonPlans: 0,
  publishedLessonPlans: 0,
  draftLessonPlans: 0
})

// 最近教案
const recentLessonPlans = ref<LessonPlan[]>([])

// 最近活动
const recentActivities = ref<Activity[]>([])

// 编辑资料表单
const editForm = reactive({
  name: '',
  email: ''
})

const editRules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ]
})

// 修改密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRules = reactive<FormRules>({
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/, message: '密码必须包含字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 头像上传配置
const avatarUploadUrl = computed(() => {
  const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3008/api'
  return `${baseUrl}/users/avatar`
})

const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${authStore.token}`
}))

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 获取角色文本
const getRoleText = (role: string) => {
  const roleMap: Record<string, string> = {
    admin: '管理员',
    teacher: '教师',
    student: '学生'
  }
  return roleMap[role] || '用户'
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    draft: 'info',
    published: 'success',
    archived: 'warning'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    draft: '草稿',
    published: '已发布',
    archived: '已归档'
  }
  return statusMap[status] || '未知'
}

// 获取活动图标
const getActivityIcon = (type: string) => {
  const iconMap: Record<string, any> = {
    create: DocumentAdd,
    update: Edit,
    delete: Delete,
    publish: Star,
    archive: Document,
    view: View,
    like: Star,
    comment: Document
  }
  return iconMap[type] || Document
}

// 获取活动图标样式类
const getActivityIconClass = (type: string) => {
  const classMap: Record<string, string> = {
    create: 'create-icon',
    update: 'update-icon',
    delete: 'delete-icon',
    publish: 'publish-icon',
    archive: 'archive-icon',
    view: 'view-icon',
    like: 'like-icon',
    comment: 'comment-icon'
  }
  return classMap[type] || ''
}

// 加载我的教案
const loadMyLessonPlans = async () => {
  loadingLessonPlans.value = true
  try {
    const { data } = await lessonPlanApi.getMyList({ page: 1, limit: 5 })
    recentLessonPlans.value = data.lessonPlans
    
    // 更新统计信息
    stats.totalLessonPlans = data.pagination.total
    stats.publishedLessonPlans = data.lessonPlans.filter(item => item.status === 'published').length
    stats.draftLessonPlans = data.lessonPlans.filter(item => item.status === 'draft').length
  } catch (error: any) {
    console.error('加载教案失败:', error)
  } finally {
    loadingLessonPlans.value = false
  }
}

// 加载活动记录
const loadActivities = async () => {
  loadingActivities.value = true
  try {
    const { data } = await userApi.getActivities({ page: 1, limit: 10 })
    recentActivities.value = data.activities
  } catch (error: any) {
    console.error('加载活动记录失败:', error)
    ElMessage.error('加载活动记录失败')
  } finally {
    loadingActivities.value = false
  }
}

// 头像上传前校验
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！')
    return false
  }
  
  return true
}

// 头像上传成功
const handleAvatarSuccess = (response: any, file: UploadFile) => {
  console.log('头像上传响应:', response)
  console.log('响应数据:', response.data)
  console.log('新头像路径:', response.data?.avatar)
  console.log('当前用户信息:', authStore.user)
  
  if (response.success && response.data) {
    // 更新 authStore 中的用户信息
    authStore.updateUserInfo({ avatar: response.data.avatar })
    console.log('更新后的用户信息:', authStore.user)
    console.log('计算后的头像URL:', avatarUrl.value)
    
    // 如果还返回了完整的用户信息，也一并更新
    if (response.data.user) {
      authStore.setUser(response.data.user)
      console.log('使用完整用户信息更新:', response.data.user)
    }
    
    ElMessage.success('头像更新成功')
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

// 头像上传失败
const handleAvatarError = (error: any, file: UploadFile) => {
  console.error('头像上传失败:', error)
  ElMessage.error('头像上传失败，请重试')
}

// 重置编辑表单
const resetEditForm = () => {
  editForm.name = userInfo.value.name || ''
  editForm.email = userInfo.value.email || ''
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.currentPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordFormRef.value?.resetFields()
}

// 更新个人资料
const handleUpdateProfile = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    updating.value = true
    
    const result = await userApi.updateProfile({ name: editForm.name })
    
    if (result.success) {
      authStore.updateUserInfo({ name: editForm.name })
      ElMessage.success('个人资料更新成功')
      showEditProfile.value = false
    } else {
      ElMessage.error(result.message || '更新失败')
    }
  } catch (error: any) {
    if (error !== false) {
      ElMessage.error(error.message || '更新失败')
    }
  } finally {
    updating.value = false
  }
}

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    changingPassword.value = true
    
    const result = await userApi.changePassword({
      currentPassword: passwordForm.currentPassword,
      newPassword: passwordForm.newPassword
    })
    
    if (result.success) {
      ElMessage.success('密码修改成功')
      showChangePassword.value = false
      resetPasswordForm()
    } else {
      ElMessage.error(result.message || '修改失败')
    }
  } catch (error: any) {
    if (error !== false) {
      ElMessage.error(error.message || '修改失败')
    }
  } finally {
    changingPassword.value = false
  }
}

// 创建教案
const createLessonPlan = () => {
  router.push('/lesson-plans/create')
}

// 查看我的教案
const viewMyLessonPlans = () => {
  router.push('/lesson-plans?author=me')
}

// 查看教案
const viewLessonPlan = (id: string) => {
  router.push(`/lesson-plans/${id}`)
}

// 编辑教案
const editLessonPlan = (id: string) => {
  router.push(`/lesson-plans/${id}/edit`)
}

// 删除教案
const deleteLessonPlan = async (lessonPlan: LessonPlan) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除教案《${lessonPlan.title}》吗？`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await lessonPlanApi.delete(lessonPlan._id)
    ElMessage.success('删除成功')
    loadMyLessonPlans()
    loadActivities() // 刷新活动记录
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 监听头像URL变化（用于调试）
watch(avatarUrl, (newVal, oldVal) => {
  console.log('头像URL变化:', { 
    旧值: oldVal, 
    新值: newVal,
    用户头像路径: userInfo.value.avatar,
    时间戳: authStore.avatarTimestamp
  })
})

// 页面加载时初始化
onMounted(() => {
  loadMyLessonPlans()
  loadActivities()
  resetEditForm()
})
</script>

<style scoped>
.profile-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.page-header {
  background: white;
  padding: 20px 24px;
  height: auto !important;
  border-bottom: 1px solid #e4e7ed;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.el-main {
  padding: 24px;
}

.profile-content {
  max-width: 1200px;
  margin: 0 auto;
}

.profile-card,
.action-card,
.content-card {
  margin-bottom: 24px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-info {
  text-align: center;
}

.avatar-section {
  position: relative;
  display: inline-block;
  margin-bottom: 20px;
}

.avatar-uploader {
  position: relative;
  cursor: pointer;
}

.user-avatar {
  border: 3px solid #f0f2f5;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s;
  font-size: 12px;
}

.avatar-uploader:hover .avatar-overlay {
  opacity: 1;
}

.basic-info {
  margin-bottom: 24px;
}

.user-name {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.user-email {
  color: #606266;
  margin: 0 0 12px 0;
}

.stats-info {
  display: flex;
  justify-content: space-around;
  margin-bottom: 24px;
  padding: 20px 0;
  border-top: 1px solid #e4e7ed;
  border-bottom: 1px solid #e4e7ed;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 24px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.register-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: #909399;
  font-size: 14px;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.quick-actions .el-button {
  justify-content: flex-start;
}

.activity-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.activity-icon {
  font-size: 16px;
}

.create-icon {
  color: #67c23a;
}

.update-icon {
  color: #409eff;
}

.delete-icon {
  color: #f56c6c;
}

.publish-icon {
  color: #e6a23c;
}

.archive-icon {
  color: #909399;
}

.view-icon {
  color: #409eff;
}

.like-icon {
  color: #e6a23c;
}

.comment-icon {
  color: #67c23a;
}

.activity-content {
  color: #606266;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  background-color: #fafbfc;
}

:deep(.el-timeline-item__wrapper) {
  padding-left: 32px;
}

:deep(.el-upload) {
  border: none;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}
</style>